<?php
namespace  Partner\Controller;

use Utuo\BackgroundController;

class PartnerBrandController extends BackgroundController {
	
	public  function _initialize() {
		$this->setControllerTitle('品牌管理');
		$this->setActionTitle(array(
			'index' => '品牌列表',
			'modify' => '品牌编辑',
		));
		$this->setActionNav(array(
				'index',
		));
	}
	
	public function getLists($is_deleted) {
		$p = $this->getPage();
		$pageSize = $this->getPageSize();
		$m = M('PartnerBrand a')->join('__PRODUCT_BRAND__ b on a.brand = b.id', "LEFT")->where(array('a.pid'=>$this->aid));
		$n = clone $m;
		$totalRows = $n->count();
		$partnerBrandList = $m->limit($pageSize)->page($p)->field('a.id,a.is_recommend,
																  case when a.name is not null then a.name when a.name is null then b.name end as name,
																  case when a.logo is not null then a.logo when a.logo is null then b.logo end as logo
																 ')->select();
		$this->showPage($totalRows, $pageSize);
		$this->assign("partnerBrandList",$partnerBrandList);
		$this->display();
	}
	
	public function addAction() {
		$this->display('save');
	}
	
	public function modifyAction() {
		$id = I('id', 0, "intval");
		$m = M('PartnerBrand a')->join('__PRODUCT_BRAND__ b on a.brand = b.id', "LEFT")->where(array('a.id'=>$id))->field('a.id,a.is_recommend,
																  case when a.name is not null then a.name when a.name is null then b.name end as name,
																  case when a.logo is not null then a.logo when a.logo is null then b.logo end as logo')->find();
		$this->assign("partnerBrand", $m);
		$this->display('save');		
	}
	
	/*public function refreshAction() {
		$brandList = M("ProductGoods a")->join("__PRODUCT_BRAND__ b on a.brand=b.id")->where(array("a.pid"=>$this->aid, "a.brand" => array('exp','is not null')))->field('b.*')->group("b.id")->select();  // 最新所有在售品牌
		$partnerBrandList = M("PartnerBrand")->where(array( 'pid' => $this->aid ))->select(); // 所有在售品牌
		// 删除非在售品牌
		foreach ($partnerBrandList as $k0 => $v0) {
			$exist = false;
			foreach ($brandList as $v) { // 检查品牌是否在售
				if ($v['id'] == $v0['brand']) {
					$exist = true;
					break;
				}
			}
			if( !$exist ) {
				unset($partnerBrandList[$k0]);
				M("PartnerBrand")->where(array('id' => $v0['id']))->delete();
			}
		}
		// 新增品牌
		foreach ($brandList as $v) {
			$exist = false;
			foreach ($partnerBrandList as $k0 => $v0) {
				if ($v['id'] == $v0['brand']) {
					$exist = true;
					break;
				}
			}
			if( !$exist ) {
				M("PartnerBrand")->add(array(
					'pid' => $this->aid,
					'brand' => $v['id'],
					'is_recommend' => 0,
				));
			}
		}
		redirect(U('PartnerBrand/index'));
	}*/
	
	// 设置状态
	public function setRecommendAction() {
		$this->ajaxSetStatus('PartnerBrand', 'is_recommend');
	}
}